package com.ossjk.config.mybatis;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.core.util.Constant;
import com.ossjk.core.util.JwtTokenUtil;

/**
 * mybatisplus自定义填充公共字段 ,即没有传的字段自动填充
 * 1.创建MyMetaObjectHandler继承com.baomidou.mybatisplus.mapper.MetaObjectHandler;
 * 2.重写insertFill和updateFill方法
 * 3.在application.yml上添加mybatis-plus.global-config.meta-object-handler=com.jkoss.example.config.mybatis.MyMetaObjectHandler
 * 4.需要自定义填充公共字段 ,即没有传的字段自动填充的,在实体类的字段上添加@TableField(value = "idcard", fill =
 * FieldFill.INSERT_UPDATE)
 */
@Component
public class BaseMetaObjectHandler extends MetaObjectHandler {

	/**
	 * 新增填充
	 */
	@Override
	public void insertFill(MetaObject metaObject) {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (!CommonUtil.isBlank(servletRequestAttributes)) {
			HttpServletRequest request = servletRequestAttributes.getRequest();
			// 创建人
			setFieldValByName("crer", request.getAttribute(Constant.REQUEST_USERID_KEY), metaObject);
			// 修改人
			setFieldValByName("mder", request.getAttribute(Constant.REQUEST_USERID_KEY), metaObject);
			// 状态 1-业务数据、2-系统数据
			setFieldValByName("state", new BigDecimal(1), metaObject);
			// 逻辑删除 1-未删除、2-已删除
			setFieldValByName("isdelete", new BigDecimal(1), metaObject);
			setFieldValByName("crtm", CommonUtil.getDate(), metaObject);
			setFieldValByName("mdtm", CommonUtil.getDate(), metaObject);
		}
	}

	/**
	 * 更新填充
	 */
	@Override
	public void updateFill(MetaObject metaObject) {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (!CommonUtil.isBlank(servletRequestAttributes)) {
			HttpServletRequest request = servletRequestAttributes.getRequest();
			// 修改人
			setFieldValByName("mder", request.getAttribute(Constant.REQUEST_USERID_KEY), metaObject);
			setFieldValByName("mdtm", CommonUtil.getDate(), metaObject);
		}
	}

}